package com.mycompany;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Random;

@Aspect
@Component
public class OrderAspect {

    // 切入点：匹配当前包下OrderService接口的所有方法
    @Pointcut("execution(* com.mycompany.OrderService.*(..))")
    public void orderPointcut() {}

    // 1. 前置增强：所有方法执行前
    @Before("orderPointcut()")
    public void beforeAdvice() {
        System.out.println("[前置增强] hello, 我是一个前置增强");
    }

    // 2. 后置增强：add和delete方法执行后
    @AfterReturning("execution(* com.mycompany.OrderService.add(..)) || " +
            "execution(* com.mycompany.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("[后置增强] bye, 我是一个后置增强");
    }

    // 3. 返回值增强：所有方法
    @AfterReturning(pointcut = "orderPointcut()", returning = "result")
    public void returnValueAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        if (result != null) {
            System.out.println("[返回值增强] 方法 " + methodName + " 的返回值: " + result);
        } else {
            System.out.println("[返回值增强] 方法 " + methodName + " 无返回值");
        }
    }

    // 4. 执行时间增强：所有方法
    @Around("orderPointcut()")
    public Object timeAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();  // 执行目标方法
        long endTime = System.currentTimeMillis();
        System.out.println("[执行时间增强] 方法 " + joinPoint.getSignature().getName() +
                " 执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限校验：add和delete方法
    @Before("execution(* com.mycompany.OrderService.add(..)) || " +
            "execution(* com.mycompany.OrderService.delete(..))")
    public void permissionCheck(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        int permission = new Random().nextInt(2);  // 0-1随机数

        if (permission == 1) {
            System.out.println("[权限校验] 无权限执行 " + methodName + " 方法，已终止");
            throw new RuntimeException("权限不足，无法执行" + methodName + "操作");
        } else {
            System.out.println("[权限校验] 有权限执行 " + methodName + " 方法");
        }
    }
}
